/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cassandrawindow;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class HandleBalanceAndPromotion {

    public static long checkDateDomainDate = 0;
    
    public void handleData() throws ParseException, InterruptedException
    {
        long first_time = System.currentTimeMillis();
        StringBuilder sb = new StringBuilder();
        //String currentDate = handleDate();
        //String currentDate = TimeUtil.getCurrentTimeInString();//2012-07-24
        String currentDate = CONSTANT.Date;
        /*
         * Lay tat ca nhung user active va tai khoan chinh ,tai khoan khuyen mai :getAllUserActive
         * lay tat ca nhung campaignid va userid lien quan :getCampaignAndUserid
         * Lay tien theo banner va domain :getMoneyByCampaignIdAndDomain
        */
        MysqlDataManager mysql = new MysqlDataManager();
        MysqlDataManagerMain mysqlMain = new MysqlDataManagerMain();
        
        //lay user active ,tai khoan khuyen mai,tai khoan chinh => cpc thuong
        Map<Integer, String> allUsers = new HashMap<>();
        allUsers = mysqlMain.getAllUserActive();

        //lay user active CPC Plus
        Map<Integer, String> allUsersCpcPlus = new HashMap<>();
        allUsersCpcPlus = mysqlMain.getAllUserActiveCpcPlus();
        //lay tat ca nhung groupid la noi bo hay doi tac
        //groupid :1 la noi bo
        //gourpid :2 la khach hang
        Map<Integer, Integer> allGroupIds = new HashMap<>();
        allGroupIds = mysqlMain.getAllGroupID();

        //lay tat ca nhung campaignid va userid lien quan
        Map<Integer, String> CampaignAndUserid = new HashMap<>();
        CampaignAndUserid = mysqlMain.getCampaignAndUserid(currentDate);
        
        //Lay tien va click theo campaign va domain
        Map<String, String> MoneyByCampaign = new HashMap<>();
        MoneyByCampaign = mysql.getMoneyByCampaignIdAndDomain(currentDate);

        //lay nhung domain hop le
        List validBanner = new ArrayList();
        validBanner = mysqlMain.getValidDomain();

        //lay nhung campaign thuoc cpc thuong
        //List CampaignCPC = new ArrayList();
        //CampaignCPC = mysqlMain.getCampaignCPC();
        
        //lay nhung campaign thuoc cpc plus
        List CampaignCPCPlus = new ArrayList();
        CampaignCPCPlus = mysqlMain.getCampaignCPCPlus();
        
        //lay gia cpcplus doi voi moi domain
        Map<String, Integer> PriceByDomainCPCPlus = new HashMap<>();
        PriceByDomainCPCPlus = mysqlMain.getPriceByDomainCPCPlus();
        
        //get every user
        Set s = allUsers.entrySet();
        Iterator it=s.iterator();
        //tinh xem group la 1 hay 2
        int flagGroup = 0;
        
        try {
            while(it.hasNext())
            {
                /*
                 * lay gia tri cpc thuong doi voi 1 user
                 */
                Map.Entry m =(Map.Entry)it.next();
                //key la userid
                int key=(Integer)m.getKey();
                //value la balance_promotion
                String valueMoneyByUserID = (String)m.getValue();
                String[] arrMoney = new String[3];
                arrMoney = valueMoneyByUserID.split("_");

                int balance = Integer.valueOf(arrMoney[0]);
                int promotion = Integer.valueOf(arrMoney[1]);
                int groupid = Integer.valueOf(arrMoney[2]);

                /*
                 * lay gia tri cpc plus doi voi 1 user
                */
                String valueMoneyByUserIDCPCPlus = allUsersCpcPlus.get(key);
                String[] arrMoneyCPCPlus = new String[3];
                arrMoneyCPCPlus = valueMoneyByUserIDCPCPlus.split("_");
                int balanceCPCPlus = Integer.valueOf(arrMoneyCPCPlus[0]);
                int promotionCPCPlus = Integer.valueOf(arrMoneyCPCPlus[1]);
                                
                //moi userid tim campaignid tuong ung
                if(CampaignAndUserid.containsKey(key))
                {
                    //mot userid co the co nhieu campaign
                    String campaignIds = CampaignAndUserid.get(key);
                    String[] arrCamp = new String[100];
                    arrCamp = campaignIds.split(",");
                    //lay ra moi campaign
                    //countCp = countCp + arrCamp.length;
                    for(int i = 0; i< arrCamp.length ; i++)
                    {
                        long campaignId = Long.valueOf(arrCamp[i]);
                        //lay moi key cua Map nay
                        //sau do parse key ra de lay domain va campId
                        //so sanh campId o tren va campid da parse
                        //neu bang nhau thi insert du lieu
                        //neu khong thi tiep tuc
                        Set s2 = MoneyByCampaign.entrySet();
                        Iterator it2 = s2.iterator();
                        while(it2.hasNext())
                        {
                            Map.Entry m2 =(Map.Entry)it2.next();
                            //key2 la campID_domain
                            String key2=(String)m2.getKey();
                            String[] arrData = new String[2];
                            arrData = key2.split("_");
                            String domain = arrData[1];
                            //System.out.println(arrData[1]);
                            try{
                                if(Long.valueOf(arrData[0]) == campaignId && validBanner.contains(domain)){
                                    //check xem là nội bộ hay khách hàng
                                    //neu la noi bo thi group = 1
                                    //neu la khach hang thi = 2
                                    if(allGroupIds.containsKey(groupid))
                                    {
                                       flagGroup = allGroupIds.get(groupid);
                                    }
                                    //count ++;
                                    //System.out.println("campaignid :" +Integer.valueOf(arrData[0]));
                                    //value la money_totalclick
                                    String dataByCampaign = (String)m2.getValue();
                                    String[] arr = new String[3];
                                    arr = dataByCampaign.split("_");
                                   
                                    //neu campaign thuoc cpc plus
                                        if (CampaignCPCPlus.contains(campaignId))
                                        {
                                            //int moneyByDomain = Integer.valueOf(arr[0]);
                                            int totalclick = Integer.valueOf(arr[1]);
                                            int totalview = Integer.valueOf(arr[2]);
                                            System.out.println("campaignid :" +campaignId+"_totalclick:"+totalclick);
                                            int moneyByDomain = PriceByDomainCPCPlus.get(domain)*totalclick;
                                            //neu <= balance thi tinh tai khoan chinh
                                            if(moneyByDomain <= balanceCPCPlus){
                                                String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick+ "," + totalview + "," + moneyByDomain +",0,"+ flagGroup +",'" + currentDate +"')";
                                                 sb.append(sqlString).append(",");
                                            }
                                            //neu tai khoan chinh < 0 thi chi tinh tai khoan khuyen mai
                                            else if(balanceCPCPlus <= 0)
                                            {
                                                //neu tai khoan khuyen mai >
                                                if(promotionCPCPlus >= moneyByDomain)
                                                {
                                                    String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick + "," + totalview +"," + 0 +"," + moneyByDomain +","+ flagGroup +",'" + currentDate +"')";
                                                    sb.append(sqlString).append(",");
                                                 //neu tai khoan khuyen mai <
                                                }else{
                                                    String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick + "," + totalview +"," + 0 +"," + promotionCPCPlus +","+ flagGroup +",'" + currentDate +"')";
                                                    sb.append(sqlString).append(",");
                                                }
                                            }
                                            //neu > tai khoan chinh va con tai khoan khuyen mai
                                            else {
                                                String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick + "," + totalview +"," + balanceCPCPlus +"," + (moneyByDomain-balanceCPCPlus)+","+ flagGroup +",'" + currentDate +"')";
                                                sb.append(sqlString).append(",");
                                            }
                                        }
                                        //neu khong thi la cpc thuong
                                        else {
                                            int moneyByDomain = Integer.valueOf(arr[0]);
                                            int totalclick = Integer.valueOf(arr[1]);
                                            int totalview = Integer.valueOf(arr[2]);
                                            //neu <= balance thi tinh tai khoan chinh
                                            if(moneyByDomain <= balance){
                                                String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick+ "," + totalview + "," + moneyByDomain +",0,"+ flagGroup +",'" + currentDate +"')";
                                                 sb.append(sqlString).append(",");
                                            }
                                            //neu tai khoan chinh < 0 thi chi tinh tai khoan khuyen mai
                                            else if(balance <= 0)
                                            {
                                                //neu tai khoan khuyen mai >
                                                if(promotion >= moneyByDomain)
                                                {
                                                    String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick + "," + totalview +"," + 0 +"," + moneyByDomain +","+ flagGroup +",'" + currentDate +"')";
                                                    sb.append(sqlString).append(",");
                                                 //neu tai khoan khuyen mai <
                                                }else{
                                                    String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick + "," + totalview +"," + 0 +"," + promotion +","+ flagGroup +",'" + currentDate +"')";
                                                    sb.append(sqlString).append(",");
                                                }
                                            }
                                            //neu > tai khoan chinh va con tai khoan khuyen mai
                                            else{
                                                String sqlString = "(" + key + "," + campaignId +",'" + domain + "'," + totalclick + "," + totalview +"," + balance +"," + (moneyByDomain-balance)+","+ flagGroup +",'" + currentDate +"')";
                                                sb.append(sqlString).append(",");
                                            }
                                        }
                                    } else {
                                        continue;
                                }
                            }catch (Exception ex){
                                //Debug.println(ex.getMessage());
                            }
                        }
                    }
                }

                if(sb.toString().length() > 10000)
                {
                   // MysqlDataManager mysql = new MysqlDataManager();
                    //xu li cho du lieu cuoi
                    String relStr = sb.toString();
                    String valInsert = relStr.substring(0, (relStr.length()-1));
                    mysql.insertBalanceAndPromotionMoney(valInsert);
                    sb.setLength(0);
                }
            }
        } catch (Exception ex) {
                 System.out.println("khong co cpcplus doi voi userid");
        }
        if(sb.toString().length() > 0)
        {
            // MysqlDataManager mysql = new MysqlDataManager();
            //xu li cho du lieu cuoi
            String relStr = sb.toString();
            String valInsert = relStr.substring(0, (relStr.length()-1));
            mysql.insertBalanceAndPromotionMoney(valInsert);
            sb.setLength(0);
        }
        long last_time = System.currentTimeMillis();
        Debug.println("Thoi gian chay  :" +(last_time-first_time));
        //System.out.println("raw campaign:"+countCp);
        //Debug.println("so campaignid :" +count);
        Debug.println("finish live budget");        
    }

    public String handleDate()
    {
        String retDate = "";//2012-07-24
        String date = TimeUtil.getCurrentTimeInStringForLog();//yyyy/MM/dd H:mm:ss

        String[] arrTime        = new String[2];
        String[] firstArrTime   = new String[3];
        String[] secondArrTime  = new String[3];

        arrTime = date.split(" ");
        firstArrTime    = arrTime[1].split(":");
        secondArrTime   = arrTime[0].split("-");
        //init checkDate if trigger from 0h -> 6h
        if(checkDateDomainDate == 0)
        {
            checkDateDomainDate = TimeUtil.getCurrentTime();
        }

        if(Integer.valueOf(firstArrTime[0]) >= 6 && Integer.valueOf(firstArrTime[0]) <= 23)
        {
            checkDateDomainDate = TimeUtil.getCurrentTime();
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+secondArrTime[2];
        } else if (Integer.valueOf(firstArrTime[0]) >= 0 && Integer.valueOf(firstArrTime[0]) < 6 && TimeUtil.getCurrentTime() >= checkDateDomainDate)
        {
            Debug.println(date + "_" + TimeUtil.getCurrentTime() + "_" + checkDateDomainDate);
            int day = Integer.valueOf(secondArrTime[2]) - 1;
            retDate = secondArrTime[0]+"-"+secondArrTime[1]+"-"+String.valueOf(day);
        }
        return retDate;
    }
}
